#!/usr/bin/python
# -*- coding: utf-8 -*-

#为方便以后移植，参数中的 key 一律为字符串格式
import logging
from google.appengine.ext import db
from google.appengine.api import memcache 
from google.appengine.api import users

import googledatabase
import getcounter
import commonfunction
import databasefunction



#===================================== 消息 =============================================

#获得新消息个数
def GetNewMessageNumber():
    LoginName = commonfunction.GetUserLoginName()
    if 1 > len(LoginName):
        return 0

    Query = db.GqlQuery('SELECT * FROM CReceiveMessage WHERE State = 0 AND LoginName = :2', LoginName)
    Results = Query.fetch(1000)
    return len(Results)


#发送一个消息，SendTo是多个用户LoginName的字符串列表
#返回发送失败的用户列表
def SendOneMessage(SendToList, Title, Content):
    LoginName = commonfunction.GetUserLoginName()
    if 1 > len(SendToList) or 1 > len(LoginName) or 1 > len(Title):
        logging.error("----------SendOneMessage 0 SendToList len = %d, LoginName = %s, Title = %s" %
                      (len(SendToList), LoginName, Title))
        return SendToList

    NewSendMsg = googledatabase.CSendOutMessage()
    NewSendMsg.Title = Title
    NewSendMsg.Content = Content
    NewSendMsg.SendTo = SendToList
    NewSendMsg.LoginName = LoginName
    NewSendMsg.State = 0
    NewSendMsg.put()

    FailUsers = []
    for ReceiveName in NewSendMsg.SendTo:
        #检查该用户是否存在
        OneUserInfo = databasefunction.GetOneUserInfo(ReceiveName)
        if OneUserInfo == None:
            FailUsers.append(ReceiveName)
            logging.error("----------SendOneMessage 1 ReceiveName = %s" % (ReceiveName))
            continue
        
        NewReceiveMsg = googledatabase.CReceiveMessage()
        NewReceiveMsg.Title = Title
        NewReceiveMsg.Content = Content
        NewReceiveMsg.From = LoginName
        NewReceiveMsg.LoginName = ReceiveName
        NewReceiveMsg.State = 0
        NewReceiveMsg.put()


    logging.error("----------SendOneMessage 2 FailUsers len = %d" % (len(FailUsers)))
    return FailUsers



#读取一条收件箱中的消息
def ReadOneReceiveMessage(ItemKey, TimeDelta):
    LoginName = commonfunction.GetUserLoginName()
    if 1 > len(LoginName):
        return None
    
    Item = databasefunction.GetOneTableItem('CReceiveMessage', ItemKey)
    if Item == None:
        return None

    if Item.LoginName != LoginName:
        return None

    if 0 == Item.State:
        Item.State = 1
        Item.put()

    #修正用户昵称
    Item.From = commonfunction.GetOneUserNickName(Item.From)
    if '' == Item.From:
        Item.From = commonfunction.GetEmptyNickName(TimeDelta)
                
    #修正时间
    Item.Date += TimeDelta
        
    return Item

#读取一条发件箱中的消息
def ReadOneSendOutMessage(ItemKey, TimeDelta):
    LoginName = commonfunction.GetUserLoginName()
    if 1 > len(LoginName):
        return None
    
    Item = databasefunction.GetOneTableItem('CSendOutMessage', ItemKey)
    if Item == None:
        return None

    if Item.LoginName != LoginName:
        return None

    #修正用户昵称
    for i in xrange(len(Item.SendTo)):
        Item.SendTo[i] = commonfunction.GetOneUserNickName(Item.SendTo[i])
        if '' == Item.SendTo[i]:
            Item.SendTo[i] = commonfunction.GetEmptyNickName(TimeDelta)
                
    #修正时间
    Item.Date += TimeDelta
        
    return Item


#读取一条删除箱中的消息
def ReadOneDeleteMessage(ItemKey, TimeDelta):
    LoginName = commonfunction.GetUserLoginName()
    if 1 > len(LoginName):
        return None
    
    Item = databasefunction.GetOneTableItem('CDeleteMessage', ItemKey)
    if Item == None:
        return None

    if Item.LoginName != LoginName:
        return None

    if 0 == Item.State:
        Item.State = 1
        Item.put()

    #修正用户昵称
    Item.From = commonfunction.GetOneUserNickName(Item.From)
    if '' == Item.From:
        Item.From = commonfunction.GetEmptyNickName(TimeDelta)
                
    #修正时间
    Item.Date += TimeDelta
        
    return Item

#删除一条收件箱中的消息，会把该消息放入删除箱
def DeleteOneReceiveMessage(ItemKey):
    LoginName = commonfunction.GetUserLoginName()
    if 1 > len(LoginName):
        return None
    
    DeleteItem = databasefunction.GetOneTableItem('CReceiveMessage', ItemKey)
    if DeleteItem == None:
        return None
    
    if DeleteItem.LoginName != LoginName:
        return None

    DeleteBoxItem = googledatabase.CDeleteMessage()
    DeleteBoxItem.Title = DeleteItem.Title
    DeleteBoxItem.Content = DeleteItem.Content
    DeleteBoxItem.From = DeleteItem.From
    DeleteBoxItem.LoginName = DeleteItem.LoginName
    DeleteBoxItem.State = DeleteItem.State
    DeleteBoxItem.Date = DeleteItem.Date
    DeleteBoxItem.put()

    DeleteItem.delete()



#删除一条发件箱中的消息
def DeleteOneSendOutMessage(ItemKey):
    LoginName = commonfunction.GetUserLoginName()
    if 1 > len(LoginName):
        logging.error("----------DeleteOneSendOutMessage 0 LoginName is %s" % (LoginName))
        return None
    
    DeleteItem = databasefunction.GetOneTableItem('CSendOutMessage', ItemKey)
    if DeleteItem == None:
        logging.error("----------DeleteOneSendOutMessage 1 DeleteItem is None")
        return None
    
    if DeleteItem.LoginName != LoginName:
        logging.error("----------DeleteOneSendOutMessage 2 DeleteItem LoginName is %s" % (DeleteItem.LoginName))
        return None

    DeleteItem.delete()


#删除一条删除箱中的消息
def DeleteOneDeleteMessage(ItemKey):
    LoginName = commonfunction.GetUserLoginName()
    if 1 > len(LoginName):
        return None
    
    DeleteItem = databasefunction.GetOneTableItem('CDeleteMessage', ItemKey)
    if DeleteItem == None:
        logging.error("----------DeleteOneDeleteMessage 1 DeleteItem is None")
        return None
    
    if DeleteItem.LoginName != LoginName:
        logging.error("----------DeleteOneDeleteMessage 2 DeleteItem LoginName is %s" % (DeleteItem.LoginName))
        return None

    DeleteItem.delete()


    
    

#接受或拒绝一个成为自己朋友的申请
def AcceptOneFriend(FriendLoginName, ResponsionState):
    if 1 != ResponsionState and 2 != ResponsionState:
        return
    
    LoginName = commonfunction.GetUserLoginName()
    FriendItem = GetOneUserFriend(LoginName, FriendLoginName)
    assert FriendItem.FriendName == LoginName
    if FriendItem == None:
        return

    if FriendItem.ResponsionState != 0:
        logging.error("-------AcceptOneFriend FriendItem.ResponsionState != 0, FriendItem.ResponsionState = %d" % (FriendItem.ResponsionState) )
        return

    FriendItem.ResponsionState = ResponsionState
    FriendItem.put()

    if 1 == ResponsionState:
        #复制一份给自己，成为自己的朋友
        NewFriendItem = googledatabase.CFriendTable()
        NewFriendItem.FriendName = FriendItem.LoginName
        NewFriendItem.LoginName = FriendItem.FriendName
        NewFriendItem.ResponsionState = 1
        NewFriendItem.ApplyType = 1
        NewFriendItem.ApplyExplain = ''
        NewFriendItem.put()    


def DeleteOneFriend(FriendLoginName, ResponsionState = -1):
    LoginName = commonfunction.GetUserLoginName()
#    logging.error("-------DeleteOneFriend FriendLoginName = %s, LoginName = %s, ResponsionState = %d" % (FriendLoginName, LoginName, ResponsionState) )
    if 1 > len(FriendLoginName) or 1 > len(LoginName):
        return
    
    Query = db.GqlQuery('SELECT * FROM CFriendTable WHERE FriendName = :1 AND LoginName = :2', FriendLoginName, LoginName)
    if -1 < ResponsionState:
        Query = db.GqlQuery('SELECT * FROM CFriendTable WHERE FriendName = :1 AND LoginName = :2 AND ResponsionState = :3', FriendLoginName, LoginName, ResponsionState)
    
    Results = Query.fetch(1)
#    logging.error("-------DeleteOneFriend Query = %s, Results = %s, Results len = %d" % (Query, Results, len(Results)) )
    
    db.delete(Results)
    

